package cn.song.controller.common;

import cn.song.model.R;
import cn.song.util.ExcelUtils;
import cn.song.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 通用服务控制器
 * 提供通用的Excel操作功能
 *
 * @author SongRenShuo
 * @date 2025/01/06
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private ExcelUtils excelUtils;

    /**
     * 获取支持的Excel库类型
     *
     * @return 支持的Excel库类型列表
     */
    @GetMapping("/excel/types")
    public R<List<String>> getSupportedExcelTypes() {
        return R.success(excelUtils.getSupportedTypes());
    }

    /**
     * 获取Excel库类型描述
     *
     * @param type Excel库类型
     * @return 类型描述
     */
    @GetMapping("/excel/type/description")
    public R<String> getExcelTypeDescription(@RequestParam String type) {
        return R.success(excelUtils.getTypeDescription(type));
    }

    /**
     * 验证Excel文件
     *
     * @param file Excel文件
     * @return 验证结果
     */
    @PostMapping("/excel/validate")
    public R<Boolean> validateExcelFile(@RequestParam("file") MultipartFile file) {
        boolean isValid = excelUtils.validateExcelFile(file);
        return R.success(isValid);
    }

    /**
     * 获取文件信息
     *
     * @param filePath 文件路径
     * @return 文件信息
     */
    @GetMapping("/file/info")
    public R<Object> getFileInfo(@RequestParam String filePath) {
        try {
            boolean exists = FileUtils.fileExists(filePath);
            double sizeMB = FileUtils.getFileSizeMB(filePath);

            java.util.Map<String, Object> fileInfo = new java.util.HashMap<>();
            fileInfo.put("exists", exists);
            fileInfo.put("sizeMB", sizeMB);
            fileInfo.put("path", filePath);

            return R.success(fileInfo);
        } catch (Exception e) {
            log.error("获取文件信息失败", e);
            return R.failed("获取文件信息失败：" + e.getMessage());
        }
    }

    /**
     * 清理临时文件
     *
     * @param directory 目录
     * @param maxAge 最大保留时间（小时）
     * @return 操作结果
     */
    @PostMapping("/file/clean")
    public R<String> cleanTempFiles(@RequestParam String directory,
                                   @RequestParam(defaultValue = "24") int maxAge) {
        try {
            FileUtils.cleanTempFiles(directory, maxAge);
            return R.success("临时文件清理完成");
        } catch (Exception e) {
            log.error("清理临时文件失败", e);
            return R.failed("清理临时文件失败：" + e.getMessage());
        }
    }

    /**
     * 获取系统信息
     *
     * @return 系统信息
     */
    @GetMapping("/system/info")
    public R<Object> getSystemInfo() {
        try {
            Runtime runtime = Runtime.getRuntime();
            long totalMemory = runtime.totalMemory();
            long freeMemory = runtime.freeMemory();
            long usedMemory = totalMemory - freeMemory;

            return R.success(new Object() {
                public final long totalMemoryMB = totalMemory / (1024 * 1024);
                public final long usedMemoryMB = usedMemory / (1024 * 1024);
                public final long freeMemoryMB = freeMemory / (1024 * 1024);
                public final int availableProcessors = runtime.availableProcessors();
            });
        } catch (Exception e) {
            log.error("获取系统信息失败", e);
            return R.failed("获取系统信息失败：" + e.getMessage());
        }
    }
}
